package component.group;

import component.AbstractComponent;
import component.Ball;
import component.Tube;

public class FindAxis {

	private ComponentGroup group = new ComponentGroup();
	
	public ComponentGroup find(Tube axis) {
		group = new ComponentGroup();
		
		traverseTube(axis, null, axis);
		
		return group;
	}
	
	private void traverseTube(Tube tube, Ball lastBall, Tube axis) {
		if (tube == null) return;
		group.add(tube);
		for (AbstractComponent component : tube.getConnectedComponents()) {
			if (component instanceof Ball && component != lastBall) {
				Ball ball = (Ball)component;
				group.add(ball);
				traverseTube(
						findNextTube(ball, tube, axis),
						ball,
						axis);
			}
		}		
	}
	
	private Tube findNextTube(Ball ball, Tube previous, Tube axis) {
		for (AbstractComponent component : ball.getConnectedComponents()) {
			if (component != previous && component instanceof Tube) {
				Tube tube = (Tube)component;
				if (tube.getOrientation().isParallell(axis.getOrientation()))
					return tube;
			}
		}
		return null;
	}
}
